package ph.com.gs3.formalistics.view.document.views;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import ph.com.gs3.formalistics.R;
import ph.com.gs3.formalistics.global.utilities.logging.FLLogger;
import ph.com.gs3.formalistics.model.vo.formcontent.EmbeddedViewData;
import ph.com.gs3.formalistics.presenter.adapters.KeyValueGroupListViewAdapter;
import ph.com.gs3.formalistics.view.customviews.DisabledScrollListView;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;

public class EmbeddedView extends LinearLayout {

	public static final String TAG = EmbeddedView.class.getSimpleName();

	private String viewId;

	private Button bCreateChildDocument;
	private DisabledScrollListView lvDocuments;

	private EmbeddedViewData embeddedViewData;

	private KeyValueGroupListViewAdapter adapter;
	private EmbeddedViewEventsListener listener;

	public EmbeddedView(Context context, EmbeddedViewData embeddedViewData) {
		super(context);

		this.embeddedViewData = embeddedViewData;

		// TODO: add condition here to display either list type or table type embed view
		initializeListType();

		setViewId(embeddedViewData.getId());
		setCreateChildDocumentActionLabel(embeddedViewData.getCreateDocumentActionLabel());
	}

	private void initializeListType() {
		LayoutInflater.from(getContext())
		        .inflate(R.layout.view_embedded_view_list_type, this, true);

		adapter = new KeyValueGroupListViewAdapter(getContext());

		bCreateChildDocument = (Button) findViewById(R.id.EmbeddedView_bCreateChildDocument);
		bCreateChildDocument.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (listener != null) {
					listener.onCreateChildDocument(embeddedViewData.getSearchFormId());
				}
			}
		});

		lvDocuments = (DisabledScrollListView) findViewById(R.id.EmbeddedView_lvDocuments);
		lvDocuments.setAdapter(adapter);
		lvDocuments.setScrollContainer(false);
		lvDocuments.setExpanded(true);

		lvDocuments.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				JSONObject selectedItem = (JSONObject) adapter.getItem(position);

				if (selectedItem.has("_id")) {
					try {
						int documentId = selectedItem.getInt("_id");
						listener.onOpenDocumentCommand(embeddedViewData.getSearchFormId(),
						        documentId);
					} catch (JSONException e) {
						FLLogger.e(TAG, "Cant open document, " + e.getMessage());
					}
				} else {
					FLLogger.e(TAG, "Cant open document, id is missing");
				}

			}

		});

		int visibility = embeddedViewData.isEnableCreateDocumentAction() ? View.VISIBLE : View.GONE;
		bCreateChildDocument.setVisibility(visibility);

		setListViewHeightBasedOnChildren(lvDocuments);

	}

	public void setData(List<JSONObject> listData) {
		adapter.setData(embeddedViewData.getViewColumns(), listData);
		adapter.notifyDataSetChanged();
	}

	/****
	 * Method for Setting the Height of the ListView dynamically. Hack to fix the issue of
	 * not showing all the items of the ListView when placed inside a ScrollView
	 ****/
	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null)
			return;

		int desiredWidth = MeasureSpec
		        .makeMeasureSpec(listView.getWidth(), MeasureSpec.UNSPECIFIED);
		int totalHeight = 0;
		View view = null;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			view = listAdapter.getView(i, view, listView);
			if (i == 0)
				view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
				        LayoutParams.WRAP_CONTENT));

			view.measure(desiredWidth, MeasureSpec.UNSPECIFIED);
			totalHeight += view.getMeasuredHeight();
		}
		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		listView.setLayoutParams(params);
		listView.requestLayout();
	}

	public void searchForEmbeddedView(String searchCompareToFieldValue) {
		listener.onSearchForEmbeddedViewRequested(searchCompareToFieldValue, this);
	}

	// =====================================================================
	// {{ Getters & Setters

	public void setViewId(String viewId) {
		this.setTag(viewId + "_container");
		this.lvDocuments.setTag(viewId);
		this.viewId = viewId;
	}

	public String getViewId() {
		return viewId;
	}

	public EmbeddedViewData getEmbeddedViewData() {
		return embeddedViewData;
	}

	public EmbeddedViewEventsListener getEventsListener() {
		return listener;
	}

	public void setCreateChildDocumentActionLabel(String label) {
		bCreateChildDocument.setText(label);
	}

	public void setEventsListener(EmbeddedViewEventsListener listener) {
		this.listener = listener;
	}

	// }}

	public static interface EmbeddedViewEventsListener {

		public void onCreateChildDocument(int formId);

		public void onSearchForEmbeddedViewRequested(String searchCompareToFieldValue,
		        EmbeddedView source);

		public void onOpenDocumentCommand(int formId, int documentId);

	}
}
